package com.offcn.service;

import com.offcn.dao.*;
import com.offcn.entity.Course;
import com.offcn.entity.CourseUser;
import com.offcn.entity.User;
import com.offcn.utils.PageUtils;

import java.util.List;


public class CourseUserServiceImpl implements CourseUserService {
    private CourseUserDao courseUser = new CourseUserDaoImpl();
    private UserDao userDao = new UserDaoImpl();
    private CourseDao courseDao = new CourseDaoImpl();

    @Override
    public PageUtils<CourseUser> findByIdAndPage(int currentPage, int pageSize, String search) {
        StringBuffer str = new StringBuffer("select cu.* from course_user as cu,user as u where cu.uid=u.uid and u.name like ?");
        int count = courseUser.findByIdAndPage(str.toString(), "%" + search + "%").size();
        str.append(" limit ?,?");
        List<CourseUser> courseUserList = courseUser.findByIdAndPage(str.toString(), "%" + search + "%", (currentPage - 1) * pageSize, pageSize);
        for (CourseUser courseUser : courseUserList) {
            User user = userDao.findById(courseUser.getUid());
            courseUser.setUser(user);
            Course course = courseDao.findById(courseUser.getCid());
            courseUser.setCourse(course);
        }
        PageUtils<CourseUser> pageUtils = new PageUtils<>(pageSize,currentPage,count,courseUserList);
        return pageUtils;
    }

    @Override
    public boolean delAll(String[] id) {
        try {
            for (String i : id) {
                int all = courseUser.delAll(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
        return true;
    }

    @Override
    public boolean updateCourseById(int id, int cid) {
        return courseUser.updateCourseById(id,cid)>0;
    }

}
